import React, { PureComponent } from 'react';
import { connect } from 'dva';
import {
  Card,
  Table,
  Button,
  Icon,
  Divider,
  Dropdown,
  Menu,
  Popconfirm,
  message,
  Drawer,
  Form,
  Col,
  Row,
  Input,
  Select,
  DatePicker,
  Modal,
  Upload
} from 'antd';
import styles from './Testcase.less';
import MenuItem from 'antd/lib/menu/MenuItem';

const { Option } = Select;
const Dragger = Upload.Dragger;
const draggerprops = {
  name: 'file',
  multiple: true,
  action: '//jsonplaceholder.typicode.com/posts/',
  onChange(info) {
    const status = info.file.status;
    if (status !== 'uploading') {
      console.log(info.file, info.fileList);
    }
    if (status === 'done') {
      message.success(`${info.file.name} file uploaded successfully.`);
    } else if (status === 'error') {
      message.error(`${info.file.name} file upload failed.`);
    }
  },
};

class DrawerForm extends React.Component {
  state = { visible: false };

  showDrawer = () => {
    this.setState({
      visible: true,
    });
  };

  onClose = () => {
    this.setState({
      visible: false,
    });
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    return (
      <div style={{ float: "right" }}>
        <Button
          type="primary"
          style={{ float: "right" }}
          onClick={this.showDrawer}
        ><Icon type="file-add" theme="filled" />
          创建用例
          </Button>
        <Drawer
          title="创建测试用例"
          width={720}
          onClose={this.onClose}
          visible={this.state.visible}
          placement="right"
          height={750}
        >
          <Form layout="vertical" hideRequiredMark>
            <Row gutter={16}>
              <Col span={24}>
                <Form.Item label="上传脚本">
                  {getFieldDecorator('upload', {
                    rules: [{ required: true, message: '请上传对应项目的测试脚本' }],
                  })(
                    <Dragger {...draggerprops}>
                      <p className="ant-upload-drag-icon">
                        <Icon type="inbox" />
                      </p>
                      <p className="ant-upload-text">点击或拖动脚本文件到此处，完成上传</p>
                      <p className="ant-upload-hint">支持单个或批量上传。请勿上传与脚本无关或其他不支持的文件</p>
                    </Dragger>
                  )}
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item label="用例标题">
                  {getFieldDecorator('title', {
                    rules: [{ required: true, message: '请输入测试用例的标题，格式：【功能】_【子功能】_【测试点】' }],
                  })(<Input placeholder="请输入用例标题" />)}
                </Form.Item>
              </Col>
              {/* <Col span={12}>
                <Form.Item label="Url">
                  {getFieldDecorator('url', {
                    rules: [{ required: true, message: 'Please enter url' }],
                  })(
                    <Input
                      style={{ width: '100%' }}
                      addonBefore="http://"
                      addonAfter=".com"
                      placeholder="Please enter url"
                    />
                  )}
                </Form.Item>
              </Col> */}
              {/* <Col span={12}>
                <Form.Item label="作者">
                  {getFieldDecorator('owner', {
                    rules: [{ required: true, message: '请选择一位作者' }],
                  })(
                    <Select placeholder="请选择一位作者">
                      <Option value="test1">作者a</Option>
                      <Option value="test2">作者b</Option>
                    </Select>
                  )}
                </Form.Item>
              </Col> */}
              <Col span={12}>
                <Form.Item label="前提条件">
                  {getFieldDecorator('testprecondition', {
                    rules: [
                      {
                        required: true,
                        message: '请输入测试用例的前提条件',
                      },
                    ],
                  })(<Input.TextArea rows={4} placeholder="请输入前提条件" />)}
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item label="测试步骤">
                  {getFieldDecorator('teststep', {
                    rules: [
                      {
                        required: true,
                        message: '请输入测试用例的执行步骤',
                      },
                    ],
                  })(<Input.TextArea rows={4} placeholder="请输入测试步骤" />)}
                </Form.Item>
              </Col>
              {/* <Col span={12}>
                <Form.Item label="类型">
                  {getFieldDecorator('type', {
                    rules: [{ required: true, message: '请选择一个测试用例类型' }],
                  })(
                    <Select placeholder="请选择一个测试用例类型">
                      <Option value="function">功能</Option>
                      <Option value="api">接口</Option>
                      <Option value="unit">单元</Option>
                    </Select>
                  )}
                </Form.Item>
              </Col> */}
              <Col span={12}>
                <Form.Item label="期望结果">
                  {getFieldDecorator('testresult', {
                    rules: [
                      {
                        required: true,
                        message: '请输入测试用例的期望结果',
                      },
                    ],
                  })(<Input.TextArea rows={4} placeholder="请输入期望结果" />)}
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              {/* <Col span={12}>
                <Form.Item label="Approver">
                  {getFieldDecorator('approver', {
                    rules: [{ required: true, message: 'Please choose the approver' }],
                  })(
                    <Select placeholder="Please choose the approver">
                      <Option value="jack">Jack Ma</Option>
                      <Option value="tom">Tom Liu</Option>
                    </Select>
                  )}
                </Form.Item>
              </Col> */}
              <Col span={24}>
                <Form.Item label="备注">
                  {getFieldDecorator('remark', {
                    rules: [
                      {
                        required: true,
                        message: '请输入测试用例的备注信息',
                      },
                    ],
                  })(<Input.TextArea rows={10} placeholder="请输入备注信息" />)}
                </Form.Item>
              </Col>
              {/* <Col span={12}>
                <Form.Item label="DateTime">
                  {getFieldDecorator('dateTime', {
                    rules: [{ required: true, message: 'Please choose the dateTime' }],
                  })(
                    <DatePicker.RangePicker
                      style={{ width: '100%' }}
                      getPopupContainer={trigger => trigger.parentNode}
                    />
                  )}
                </Form.Item>
              </Col> */}
            </Row>
          </Form>
          <div
            style={{
              position: 'absolute',
              left: 0,
              bottom: 0,
              width: '100%',
              borderTop: '1px solid #e9e9e9',
              padding: '10px 16px',
              background: '#fff',
              textAlign: 'right',
            }}
          >
            <Button onClick={this.onClose} style={{ marginRight: 8 }}>
              取消
            </Button>
            <Button onClick={this.onClose} type="primary">
              保存
            </Button>
          </div>
        </Drawer>
      </div>
    );
  }
}

const DrawerForCaseAdd = Form.create()(DrawerForm);
/* eslint react/no-array-index-key: 0 */

const data = [];
const date = new Date();
for (let i = 0; i < 20; i++) {
  data.push({
    case_id: `testcase-00${(i + 1).toString()}`,
    case_title: `用例标题${i}`,
    case_history: `${Math.floor(Math.random() * i)}/${Math.floor(Math.random() * i)}`,
    case_modifytime: `
    ${date.getFullYear()}-${date.getMonth()}-${date.getDate() + i} 
    ${date.getHours() + Math.floor(Math.random() * i)}:${date.getMinutes() + Math.floor(Math.random() * i)}:${date.getSeconds() + Math.floor(Math.random() * i)}`,
  })
}

const confirm = (e) => {
  console.log(e);
  message.success('用例删除成功');
}
const cancel = (e) => {
  console.log(e);
  // message.error('取消删除');
}

const DeleteModal = Modal.confirm
const showDeleteConfirm = () => {
  DeleteModal({
    title: '确定删除选中的用例?',
    content: '用例一旦删除无法恢复',
    okText: '确定',
    okType: 'danger',
    cancelText: '取消',
    onOk() {
      console.log('OK');
    },
    onCancel() {
      console.log('Cancel');
    },
  });
}

const menu = (
  <Menu>
    <MenuItem>
      <a>导出</a>
    </MenuItem>
    <MenuItem>
      <a onClick={showDeleteConfirm}>删除</a>
    </MenuItem>
    <MenuItem>
      <a>拷贝</a>
    </MenuItem>
  </Menu>
)

@connect()

export default class Testcase extends PureComponent {
  state = {
    selectedRowKeys: [], // Check here to configure the default column
    loading: false,
    filteredInfo: null,
    sortedInfo: null,
  };

  onSelectChange = (selectedRowKeys) => {
    console.log('selectedRowKeys changed: ', selectedRowKeys);
    this.setState({ selectedRowKeys });
  }

  handleChange = (pagination, filters, sorter) => {
    console.log('Various parameters', pagination, filters, sorter);
    this.setState({
      filteredInfo: filters,
      sortedInfo: sorter,
    });
  }


  render() {
    let { sortedInfo, filteredInfo } = this.state;
    sortedInfo = sortedInfo || {};
    filteredInfo = filteredInfo || {};
    const columns = [{
      title: 'id',
      dataIndex: 'case_id',
      key: 'case_id',
      sorter: (a, b) => a.case_id.length - b.case_id.length,
      sortOrder: sortedInfo.columnKey === 'case_id' && sortedInfo.order,
    }, {
      title: '标题',
      dataIndex: 'case_title',
      key: 'case_title',
      filters: [
        { text: '用例标题1', value: '用例标题1' },
        { text: '用例标题2', value: '用例标题2' },
      ],
      filteredValue: filteredInfo.case_title || null,
      onFilter: (value, record) => record.case_title.includes(value),
    }, {
      title: '执行历史（成功/失败）',
      dataIndex: 'case_history',
      key: 'case_history',
      sorter: (a, b) => a.case_history.length - b.case_history.length,
      sortOrder: sortedInfo.columnKey === 'case_history' && sortedInfo.order,
    }, {
      title: '更新时间',
      dataIndex: 'case_modifytime',
      key: 'case_modifytime',
      sorter: (a, b) => a.case_modifytime.length - b.case_modifytime.length,
      sortOrder: sortedInfo.columnKey === 'case_modifytime' && sortedInfo.order,
    }, {
      title: '测试脚本',
      key: 'testscript',
      render: () => (
        <div>
          <a href="javascript:;">
            testscript_demo.zip
            </a>
        </div>
      ),
    }, {
      title: '操作',
      key: 'operation',
      render: () => (
        <div>
          <Icon onClick={ DrawerForCaseAdd } type="eye" theme="twoTone" />
          <Divider type="vertical" />
          <Icon onClick={ DrawerForCaseAdd } type="edit" theme="twoTone" />
          <Divider type="vertical" />
          <Popconfirm
            title="确定删除当前用例？"
            onConfirm={confirm}
            onCancel={cancel}
            okText="是"
            cancelText="否">
            <Icon type="delete" theme="twoTone" />
          </Popconfirm>
        </div>
      ),
    }];

    const { loading, selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    const hasSelected = selectedRowKeys.length > 0;

    return (
      <div className={styles.coverCardList}>
        <Card bordered={false}>
          <Dropdown disabled={!hasSelected} overlay={menu} placement="bottomLeft">
            <Button
              loading={loading}
            >
              批量操作
            </Button>
          </Dropdown>
          <span style={{ marginLeft: 8 }}>
            {hasSelected ? `Selected ${selectedRowKeys.length} items` : ''}
          </span>
          <DrawerForCaseAdd />
          <Table
            size="small"
            rowSelection={rowSelection}
            columns={columns}
            dataSource={data}
            onChange={this.handleChange}
            style={{ marginTop: 30 }} />
        </Card>
      </div>
    );
  }
}